import React, { PureComponent } from "react";
import { connect } from "dva";
import moment from "moment";
import { Modal, Row, Col, Form, Input,  Icon, Button, message, Select, DatePicker,Cascader} from "antd";
import PickPostion from './PickPostion';
import PickPostionOpenLayers from './PickPostionOpenLayers';
import locationIcon from '../../../assets/img/location.svg';

const FormItem = Form.Item;
const { TextArea } = Input;
const Search = Input.Search;
const { Option } = Select;
const { RangePicker } = DatePicker;



function fn(data, pid) {
  let result = [], temp;
  if(data && pid){
    for (let i in data) {
      if (data[i].parentId == pid) {
        result.push(data[i]);
        temp = fn(data, data[i].districtId);
        if (temp.length > 0) {
          data[i].children = temp;
        }
      }
    }
  }
  return result;
}

Array.prototype.ToTreeJson = function (pid) {
  let result = [], temp;
  for (let i in this) {
    if (this[i].parentId == pid) {
      result.push(this[i]);
      temp = fn(this, this[i].districtId);
      if (temp.length > 0) {
        this[i].children = temp;
      }
    }
  }
  return result;
}


@connect(({ point, global })  => ({
  loading:point.loading,
  detaildata:point.detaildata,
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
}))
@Form.create()
export default class Add extends PureComponent {
  constructor(props) {
    super(props);
    this.state={
      mapmodel:false,
      longitude:null,
      latitude:null,
    }
  }

  onRef = (ref) => {
    this.pickPostion = ref;
  }
  componentDidMount() {
    const {dispatch} = this.props;
    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });
    // 区域列表
    dispatch({
      type: 'global/fetch_select_district',
    });
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.visible === true && this.props.visible === false) {
      // this.props.dispatch({
      //   type: "system_cooperation/fetch_all_collaborate"
      // });

      // 编辑时 读取详情
      if (nextProps.detailId && nextProps.detailId !== 0) {
          this.props.dispatch({
            type: "point/fetch_point_info",
            payload: {
              pointId: nextProps.detailId
            }
          }).then(()=>{
            this.setState({
              longitude:this.props.detaildata.longitude,
              latitude:this.props.detaildata.latitude,
            })
          })
      }
    }
  }

  handleSubmit(e) {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch, detailId } = this.props;
        if(values.qualityTime){
          values.qualityBeginTime = values.qualityTime[0].unix() * 1000;
          values.qualityEndTime = values.qualityTime[1].unix() * 1000;
        }
        if(values.districtId && values.districtId.length>0){
          values.districtId=values.districtId[values.districtId.length-1];
        }

        const pointId = detailId === 0 ? undefined : detailId;
        const action = detailId === 0 ? 'add' : 'edit';
        dispatch({
            type: `point/${action}_point`,
            payload: {
              ...values,
              pointId,
              qualityTime:undefined,
            }
          })
          .then(() => {
            this.handleReset();
            this.handleCancel();
            this.props.callback();
          });
      }
    });
  }

  handleReset = () => {
    this.props.form.resetFields();
  };

  handleCancel = () => {
    this.handleReset();
    this.props.onCancel(false);
  };


  initArrObject = (arr, name) => {
    if (arr) {
      let str = [];
      for (let i of arr) {
        str.push(i[name]);
      }
      return str.join("、");
    }
  };

  getDistrictArray= (lastid) =>{
    const result = lastid ? this.getparentId(lastid,[lastid]) : undefined;
    return result;
  }

  getparentId = (chilrenid,arr) =>{
    const { selectSource:{districtData} } = this.props;
    const parentId = districtData.find(item=>item.districtId==chilrenid);
    if(parentId && parentId.parentId  && parentId.parentId!="0"){
      arr.unshift(parentId.parentId);
      this.getparentId(parentId.parentId,arr);
    }
    return arr;
  }


  // 通过地图选点
  handleChooseByMap = () =>{
    this.setState({
      mapmodel:true
    })

  }

  handleMapCancel = () =>{
    this.setState({
      mapmodel:false
    })
  }

  getPoint = () => {
    this.pickPostion.addPoint();
  }

  handleSetPostion = (value) =>{
    // console.log(value);
    this.setState({
      longitude:value.lng,
      latitude:value.lat,
    })
  }

  handleMapSuccess = () =>{
    const { form } = this.props;
    const { longitude, latitude} = this.state;
    form.setFieldsValue({
      longitude,
      latitude,
    })
    this.handleMapCancel();
  }

  render() {
    const { visible, loading, detailId, detaildata, dictionaries, selectSource } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { mapmodel, longitude, latitude } = this.state;

    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 }
    };

    const formItemLayoutOne = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 }
    };




    return (
      <div>
        <Modal
          title={detailId === 0 ? "新增点位" : "编辑点位"}
          okText={detailId === 0 ? "提交" : "编辑"}
          visible={visible}
          onOk={this.handleSubmit.bind(this)}
          confirmLoading={loading.model_submit}
          onCancel={this.handleCancel}
          width={600}
        >
          <Form layout="horizontal">
            <Row gutter={24}>
              <Col span={12}>
                <FormItem {...formItemLayout} label="点位编号" colon={false}>
                  {getFieldDecorator("pointCode", {
                    initialValue: detailId === 0 ? null : detaildata.pointCode,
                    rules: [
                      { required: true, message: "请输入点位编号" },
                    ]
                  })(
                    <Input placeholder="请输入点位编号" />
                  )}
                </FormItem>
              </Col>

              <Col span={12}>
                <FormItem {...formItemLayout} label="点位名称" colon={false}>
                  {getFieldDecorator("pointName", {
                    initialValue: detailId === 0 ? null : detaildata.pointName,
                    rules: [
                      { required: true, message: "请输入点位名称" },
                    ]
                  })(
                    <Input placeholder="请输入点位名称" />
                  )}
                </FormItem>
              </Col>

              <Col span={12}>
                <FormItem {...formItemLayout} label="点位类型" colon={false}>
                  {getFieldDecorator("pointType", {
                    initialValue: detailId === 0 ? undefined : (detaildata.pointType && detaildata.pointType),
                    rules: [
                       { required: true, message: "请选择点位类型" },
                    ]
                  })(
                    <Select placeholder="请选择点位类型"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            style={{ width: '100%' }}>
                      {dictionaries.pointType && dictionaries.pointType.map(item => (
                        <Option key={item.value} value={item.value}>{item.label}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={12}>
                <FormItem {...formItemLayout} label="运营商" colon={false}>
                  {getFieldDecorator("operatorInfo", {
                    initialValue: detailId === 0 ? undefined : (detaildata.operatorInfo && detaildata.operatorInfo),
                    rules: [
                       { required: true, message: "请选择运营商" },
                    ]
                  })(
                    <Select placeholder="请选择运营商"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            style={{ width: '100%' }}>
                      {dictionaries.operatorInfo && dictionaries.operatorInfo.map(item => (
                        <Option key={item.value} value={item.value}>{item.label}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={12}>
                <FormItem {...formItemLayout} label="所属区域" colon={false}>
                  {getFieldDecorator("districtId", {
                    initialValue: detailId === 0 ? undefined : (detaildata.districtId && this.getDistrictArray(detaildata.districtId)),
                    rules: [
                      { required: true, message: "请选择所属区域" },
                    ]
                  })(
                    <Cascader
                      options={selectSource.districtData && selectSource.districtData.length>0 ? selectSource.districtData.ToTreeJson(0) : []}
                      allowClear={true}
                      placeholder={"请选择所属区域"}
                      fieldNames={{label: 'districtName', value: 'districtId', children: 'children' }}
                      getPopupContainer={triggerNode => triggerNode.parentNode}
                    />
                  )}
                </FormItem>
              </Col>



              <Col span={12} className="loaction">
                <FormItem {...formItemLayout} label="x坐标" colon={false}>
                  {getFieldDecorator("longitude", {
                    initialValue: detailId === 0 ? null : detaildata.longitude,
                    rules: [
                      { type:"float", message: "必须数值" }
                      // { pattern: "^[0-9]+(.[0-9]{6})?$", message: "必须为6位小数数值" },
                      // { required: true, message: "请输入点位名称" },
                    ]
                  })(
                    <Search placeholder="请输入x坐标（经度）"
                           enterButton={<img style={{height:15,marginBottom:3}} src={locationIcon} />}
                           onSearch={this.handleChooseByMap}
                    />
                  )}
                </FormItem>
              </Col>


              <Col span={12}  className="loaction">
                <FormItem {...formItemLayout} label="y坐标" colon={false}>
                  {getFieldDecorator("latitude", {
                    initialValue: detailId === 0 ? null : detaildata.latitude,
                    rules: [
                      { type:"float", message: "必须数值" }
                      // { pattern: "^[0-9]+(.[0-9]{6})?$", message: "必须为6位小数数值" },
                      // { required: true, message: "请输入点位名称" },
                    ]
                  })(
                    <Search placeholder="请输入y坐标（维度）"
                            enterButton={<img style={{height:15,marginBottom:3}} src={locationIcon} />}
                            onSearch={this.handleChooseByMap}
                    />
                  )}
                </FormItem>
              </Col>



              <Col span={12}>
                <FormItem {...formItemLayout} label="维保单位" colon={false}>
                  {getFieldDecorator("maintenanceId", {
                    initialValue: detailId === 0 ? undefined : (detaildata.maintenanceId && detaildata.maintenanceId),
                    rules: [
                       { required: true, message: "请选择维保单位" },
                    ]
                  })(
                    <Select placeholder="请选择维保单位"
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            style={{ width: '100%' }}>
                      {selectSource.maintenance && selectSource.maintenance.map(item => (
                        <Option key={item.maintenanceId} value={item.maintenanceId}>{item.maintenanceName}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>

              <Col span={12}>
                <FormItem {...formItemLayout} label="质保期（免费）" colon={false}>
                  {getFieldDecorator("qualityTime", {
                    initialValue: this.detailId === 0 ? undefined : (detaildata.qualityBeginTime && detaildata.qualityEndTime ?  [moment(Number(detaildata.qualityBeginTime)),moment(Number(detaildata.qualityEndTime))]  : undefined),
                  })(
                    <RangePicker
                      format="YYYY-MM-DD"
                      placeholder={['开始时间', '结束时间']}
                      style={{ width: "100%" }}
                    />
                  )}
                </FormItem>
              </Col>


              <Col span={24}>
                <FormItem {...formItemLayoutOne} label="备注" colon={false}>
                  {getFieldDecorator("remarks", {
                    initialValue: detailId === 0 ? undefined : detaildata.remarks,
                    rules: [{ max: 200, message: "不超过200个字" }]
                  })(
                    <TextArea
                      placeholder="请输入备注内容"
                      autosize={{ minRows: 3, maxRows: 6 }}
                    />
                  )}
                </FormItem>
              </Col>




            </Row>
          </Form>

        </Modal>


        <Modal
          title="请拖动标签，选择点位"
          width={900}
          style={{ top: 20}}
          bodyStyle={{ padding:0 }}
          visible={mapmodel}
          destroyOnClose={true}
          onOk={this.handleMapSuccess}
          onCancel={this.handleMapCancel}
          footer={[
            <Button key="getPoint" onClick={this.getPoint}>获取点位</Button>,
            <Button key="cancel" onClick={this.handleMapCancel}>取消</Button>,
            <Button key="ok" onClick={this.handleMapSuccess}>确定</Button>,
          ]}
        >
        <PickPostionOpenLayers onRef={this.onRef} setPosition={this.handleSetPostion}
                       originPos={{lng: longitude, lat:latitude}}
          />
          {/* <PickPostion setPosition={this.handleSetPostion}
                       originPos={{lng: longitude, lat:latitude}}
          /> */}
        </Modal>
      </div>
    );
  }
}
